package com.wsl.server;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


import javax.xml.soap.SOAPException;
import java.util.*;

/**
 * @Author:wangshuliang
 * @Description:
 * @Date:Created in 17:09 2019/5/21
 * @Modified by:
 */
public class AuthInterceptor  extends AbstractPhaseInterceptor<SoapMessage> {
    private static final String USERNAME="root";

    private static final String PASSWORD="admin";

    public AuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        List<Header> headers = null;
        String username = null;
        String password= null;
        try{
            headers = soapMessage.getHeaders();
        }catch (Exception e){
            System.out.println("getSOAPHeader error"+e.getMessage());
        }
        if (headers == null){
            throw  new Fault(new IllegalArgumentException("找不到header，无法验证用户信息"));
        }

        //获取用户名和密码
        for (Header header : headers) {
            SoapHeader soapHeader =(SoapHeader)header;
            Element element= (Element) soapHeader.getObject();
            NodeList usernameNode = element.getElementsByTagName("username");
            NodeList pwdNode = element.getElementsByTagName("password");
            username= usernameNode.item(0).getTextContent();
            password = pwdNode.item(0).getTextContent();
            if (StringUtils.isEmpty(username)|| StringUtils.isEmpty(password)){
                throw new Fault(new IllegalArgumentException("用户信息为空"));
            }
        }
        //校验用户名和密码
        if(!(username.equals(USERNAME) && password.equals(PASSWORD))){
            SOAPException soapException = new SOAPException("认证失败");
            System.out.println("用户认证信息错误");
            throw  new Fault(soapException);
        }


    }
}
